package com.neo.util;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IrrUtil {
    private double MINDIF = 0.001;

    private int LOOPNUM = 2000;

    private static int period = 0;

    @SuppressWarnings("rawtypes")
    private List netCash = new ArrayList();

    public  static double ceshi(List list){
        IrrUtil aa = new IrrUtil(list,21);
        return aa.calculator();
    }
    /*public static void main(String[] args) {
         List list = new ArrayList();
       Double[] strings2={-8344.66,2410.8442945600086,1084.6850492280046,13768.980177490543,1977.943587567268,1937.355717393909,908.1757444113209,
               1729.1382381054245,1891.5535588623607,1971.6658030361086,2017.380097589742,1285.2744074669226,2102.819682606795,2144.3540062884613,
               2186.7531376538454,2220.83432226923,3948.794309280769,4667.068161376283,4610.1260934679485,4551.701624833333,9505.374183250002};
         //-43345 	4522 	5085 	17692 	5788 	5638 	4334 	5058 	5123 	5108 	5055
         // 4226 	4946 	4892 	4836 	4780 	3949 	4667 	4610 	4552 	9505
        Double[] strings={-8344.66,2410.844295,1084.840048 ,13769.28612,	1978.004971	,1937.620185	,908.1992837	,1729.319962,	1891.493209,
                1971.708781,	2017.085142	,1284.96336,	2102.791089	,2144.157339	,2186.640614	,2221.055616	,3948.864763	,
                4667.202907,
                4609.803143	,4551.849334,	9505.44054};
        List<Double> stringB = Arrays.asList(strings2);
        System.out.println(stringB);
         IrrUtil  aa = new IrrUtil(stringB,21);
         System.out.println(aa.ceshi(stringB));
     }*/
    @SuppressWarnings("rawtypes")
    public IrrUtil(List netCashArr, int interval) {
        super();
        netCash = netCashArr;
        period = 12/interval;
    }

    private double NPV(double r) {

        double npv = 0;

        if (netCash.size() != 0) {
            for (int count = 0; count < netCash.size(); count++) {
                npv += Double.valueOf(netCash.get(count).toString()) / Math.pow(1 + r, count);
            }
            return npv;
        }
        return Double.NaN;
    }

    public double calculator() {

        double irr = 0;
        double r1 = new BigDecimal("0.1").doubleValue();
        double r2 = new BigDecimal("0.09").doubleValue();
        double npv1 = NPV(r1);
        double npv2 = NPV(r2);
        //System.out.println(netCash+"--");
        int count = 0;
        while (Math.abs(npv2) > MINDIF & count < LOOPNUM) {
            irr = r2 - npv2 * (r2 - r1) / (npv2 - npv1);
            r1 = r2;
            r2 = irr;
            npv1 = npv2;
            npv2 = NPV(r2);
            count++;
            // System.out.println(count+"--");
        }
        // System.out.println(irr*period+"--");
        if (Math.abs(npv2) < MINDIF & count <= LOOPNUM)

            //return irr * period ;
            return irr;
        else
            return Double.NaN;
    }
}